# -*- coding: utf-8 -*-
"""
 ----------------------------------------
|File Name:     spiderBaseMethod
|Author:        WYT
|date:          2020/8/5
 ----------------------------------------
|  Change Activity:
|                   2020/8/5:
-----------------------------------------
"""

import datetime
import re
import time

import pandas as pd

from collections import Iterable
from decimal import Decimal

from util.selenium.webdriver.common.by import By
from util.selenium.webdriver.support.select import Select
from util.selenium.webdriver.support.wait import WebDriverWait
from util.selenium.webdriver.support import expected_conditions as EC
from util.selenium.common.exceptions import NoSuchElementException, TimeoutException

from util.g import g
# from settings import data_path


class bm():

    @staticmethod
    def wait(driver=None, ele_loc=(), time=10):
        for i in range(5):
            try:
                WebDriverWait(driver=driver, timeout=time, poll_frequency=0.5).until(
                    EC.presence_of_all_elements_located(ele_loc))
            except TimeoutException as err:
                g.logger.error("TimeoutException: {} err: {} file: {} lines: {}" \
                               .format(ele_loc, err, err.__traceback__.tb_frame.f_globals.get("__file__"),
                                       err.__traceback__.tb_lineno))
            else:
                break
        else:
            pass

    @staticmethod
    def input(driver=None, ele_loc=(), keys=""):
        bm.wait(driver=driver, ele_loc=ele_loc)
        ele = driver.find_element(*ele_loc)
        ele.clear()
        ele.send_keys(keys)

    @staticmethod
    def click(driver=None, ele_loc=()):
        try:
            bm.wait(driver=driver, ele_loc=ele_loc)
            click_js: str = None
            if ele_loc[0] == By.CSS_SELECTOR:
                click_js = "document.querySelector('{}').click()".format(ele_loc[1])
                driver.execute_script(click_js)
            elif ele_loc[0] == By.XPATH:
                click_js = '''document.evaluate("{}", document).iterateNext().click()'''.format(ele_loc[1])
                driver.execute_script(click_js)
            else:
                driver.find_element(*ele_loc).click()
        except Exception as err:
            msg = "error: {} file: {} lines: {} click_js: {}".format(err,
                                                                     err.__traceback__.tb_frame.f_globals["__file__"],
                                                                     err.__traceback__.tb_lineno, click_js)
            g.logger.error(msg)
            raise Exception(msg)

    @staticmethod
    def get_ele(driver=None, ele_loc=(), time=10):
        try:
            bm.wait(driver=driver, ele_loc=ele_loc, time=time)
            a = driver.find_element(*ele_loc)
        except Exception as err:
            msg = "error: {} file: {} lines: {} title: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                                  err.__traceback__.tb_lineno,
                                                                  driver.find_element(By.CSS_SELECTOR,
                                                                                      "head title").text)
            g.logger.error(msg)
            raise Exception(msg)
        return a

    @staticmethod
    def switch_frame(driver=None, ele_loc=()):
        try:
            bm.wait(driver=driver, ele_loc=ele_loc)
            driver.switch_to.frame(driver.find_element(*ele_loc))
        except Exception as err:
            print("err\n{}".format(driver.find_element(By.CSS_SELECTOR, "head title").text))

    # # # 详情页 跳转到 iframe 中
    @staticmethod
    def detail_switch_iframe(driver=None):
        # detail_main_iframe_loc = (By.CSS_SELECTOR, 'iframe#submainframe')
        # bm.wait(driver=driver, ele_loc=detail_main_iframe_loc)
        # driver.switch_to.frame(driver.find_element(*detail_main_iframe_loc))
        pass

    @staticmethod
    def is_exist(driver=None, ele_loc=()):
        try:
            driver.find_element(*ele_loc)
        except NoSuchElementException as e:
            return False
        else:
            return True

    @staticmethod
    def select_value(driver=None, ele_loc=(), keys=""):
        bm.wait(driver=driver, ele_loc=ele_loc)
        select_ele = driver.find_element(*ele_loc)
        Select(select_ele).select_by_visible_text(keys)

    @staticmethod
    def get_ids(id_str=''):
        re_rule = '\d+'
        if isinstance(id_str, Iterable):
            id_str = ''.join(id_str)
        if id_str.isdigit():
            return int(id_str)
        res = re.findall(re_rule, id_str, re.S)
        if not res:
            return ''
        if len(res) == 1:
            return int(res[0])
        else:
            a = ','.join([str(int(i)) for i in res])
            return a

    @staticmethod
    def sta_get_ids(id_str=''):
        re_rule = '\d+'
        if isinstance(id_str, Iterable):
            id_str = ''.join(id_str)
        if '其他' in id_str:
            id_str = id_str.replace('其他', '0')
        res = re.findall(re_rule, id_str, re.S)
        if not res:
            return ''
        if len(res) == 1:
            return int(res[0])
        else:
            a = ','.join([str(int(i)) for i in res])
            return a

    @staticmethod
    def get_num(s=""):
        re_rule = "\d+"
        if isinstance(s, list):
            s = "".join(s)
        if s.isdigit():
            return int(s)
        if s.replace(".", "").isdigit():
            return float(s)
        res = re.findall(re_rule, s, re.S)
        if not res:
            return ""
        if len(res) == 1:
            return int(res[0])
        else:
            return res

    # @staticmethod
    # def read_csv(filename=''):
    #     data = pd.read_csv(filepath_or_buffer=data_path + filename, encoding='gb2312')
    #     df = pd.DataFrame(data)
    #     return df

    @staticmethod
    def get_int(int_str=''):
        if isinstance(int_str, Iterable):
            int_str = ''.join(int_str)
        if int_str.isdigit():
            return int(int_str)
        rule_str = '\d+'
        res = re.search(rule_str, int_str)
        if not res:
            return 0
        return int(res.group())

    @staticmethod
    def get_float(float_str=''):
        if isinstance(float_str, Iterable):
            float_str = ''.join(float_str)
        # # # TODO 这里判断 该字符串是否为浮点数。
        if not float_str:
            return Decimal("0.0")
        if type(float_str) == str:
            if float_str.replace('.', '').isdigit():
                return Decimal(float_str)
        rule_str = '\d+\.?\d+'
        res = re.search(rule_str, float_str)
        if not res:
            return Decimal('0.0')

        return Decimal(res.group())

    @staticmethod
    def get_float_str(s):
        try:
            if isinstance(s, list):
                s = ''.join(s)
            # # # TODO 这里判断 该字符串是否为浮点数。
            if not s:
                return "0.00"
            if type(s) == str:
                if s.replace('.', '').isdigit():
                    return "%.2f" % float(s)
            rule_str = '\d+\.?\d+'
            res = re.search(rule_str, s)
            if not res:
                return "0.00"

            return "%.2f" % float(res.group())
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                        err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)

    @staticmethod
    def get_hanzi(aim_str="", aim_type="str"):
        if isinstance(aim_str, Iterable):
            aim_str = "".join(aim_str)

        rule_str = "[\u4E00-\u9FA5]+"
        result = re.findall(rule_str, aim_str)
        if aim_type == "str":
            return "".join(result)
        elif aim_type == "list":
            return result
        else:
            raise Exception("type error")

    @staticmethod
    def get_page_num(driver=None):
        g.page_css = '.pagination.pull-right li.active-a a'
        page_nums_loc = (By.CSS_SELECTOR, g.page_css)

        page_nums = driver.find_elements(*page_nums_loc)

        return page_nums

    @staticmethod
    def year_objs(driver=None):

        year_btn_loc = (By.CSS_SELECTOR, '.tab-box ul#attendance li')
        g.year_css = year_btn_loc[1]

        y = driver.find_elements(*year_btn_loc)
        return y

    @classmethod
    def get_value(cls, cursor=None, typ='', label=''):
        sql = f'''
        select value from sys_dict where type="{typ}" and label="{label}";
        '''
        # print(sql)
        if not cursor:
            g.logger.error('NameError: cursor is not defind. --custom-- in bm.get_value')
        count = cursor.execute(sql)
        if not count:
            g.logger.error(f'{typ} in sys_dict, label not equal {label}')
            return None

        result = cursor.fetchone()
        if isinstance(result, Iterable) and len(result) == 1:
            result = result[0]
        if type(result) == str:
            result = int(result)
        cursor.close()
        return result

    @staticmethod
    def get_year(st=[]):
        if isinstance(st, Iterable):
            st = ''.join(st)

        rule_s = re.compile('\d+')
        res = rule_s.search(st)
        if not res:
            g.logger.error(f'error:{st} - this str has not include year info. --custom-- in handle_main_case.get_year')
        return int(res.group())

    @staticmethod
    def str_to_date(s=''):
        if isinstance(s, Iterable):
            s = ''.join(s)
        if len(s) != 10:
            s = s.replace(' ', '').replace('\n', '').replace('\t', '')
        if not s:
            return ''
        rule = "\d{4}-\d{2}-\d{2}"
        res = re.search(rule, s)
        if res:
            return res.group()
        return s

    @staticmethod
    def str_to_year(s=''):
        if isinstance(s, Iterable):
            s = ''.join(s).replace(' ', '').replace('\n', '').replace('\t', '')
        if len(s) == 4:
            return int(s) if s.isdigit() else None
        if not s:
            return 0
        s = s[:4]
        return int(s) if s.isdigit() else None

    @staticmethod
    def handle_domain(domain=None):
        if isinstance(domain, Iterable):
            domain = ''.join(domain)
        if not domain:
            return ""
        b = domain.replace(' ', '').replace('/\n', ',').replace("\t/", ",").replace('\t', '').replace('\n', '')
        return b

    @staticmethod
    def handle_rd_date(date_str):
        if isinstance(date_str, list):
            date_str = "".join(date_str)
        rule = "\d{4}-\d{2}-\d{2}"
        res = re.findall(rule, date_str)
        a = time.mktime(time.strptime(res[0], "%Y-%m-%d"))
        b = time.mktime(time.strptime(res[1], "%Y-%m-%d"))
        if a > b:
            res[0], res[1] = res[1], res[0]
        return res

    @staticmethod
    def iterable_to_str(li=None):
        if isinstance(li, Iterable):
            return "".join(li)
        elif type(li) != str:
            return str(li)

    @staticmethod
    def get_first(li=None):
        if not li:
            return None
        if isinstance(li, Iterable):
            return li[0]
        else:
            return li
    @staticmethod
    def join_and_repalce(li):
        if type(li) == str:
            return li
        a = ''.join(li)
        b = a.replace(' ', '').replace('\n', '').replace("\r", "").replace('\t', '').replace('\xa0', '')
        return b

    @staticmethod
    def check_cc(te):
        rule_m = re.compile(u'[\u4e00-\u9fa5]+')

        res = rule_m.search(te, re.S)

        return False if not res else True

    @staticmethod
    def handel_long_text(text=[]):

        _=[text.pop(i) for i, e in enumerate(text) if not bm.check_cc(e)]

        a = ''.join(text)
        return a


if __name__ == '__main__':
    aim = """
    a = "2020-02-27"
    

	                                    	C 制造业

									"""
    a = "2020-02-27"
    print(bm.str_to_date(s=a))

    print(datetime.datetime.strptime(a, "%Y-%m-%d"))
    # print(f"-{aim}-")
    # # print(bm.str_to_date(s=['2017-06-27']))
    # print(bm.get_hanzi(aim_str=aim))

